#!/bin/bash

# Simplified Docker entrypoint for PostgreSQL MCP Server with Nacos support
# Based on original docker-entrypoint.sh with Nacos integration support

set -e

# Function to load .env file from config directory
load_env_file() {
    local env_files=(
        "/app/config/.env"
        "/app/config/.env.local"
        "/app/.env"
    )

    for env_file in "${env_files[@]}"; do
        if [[ -f "$env_file" ]]; then
            echo "Loading environment variables from: $env_file" >&2
            # Set environment variables, preserving existing ones
            set -a
            source "$env_file"
            set +a
            echo "✓ Environment variables loaded from $env_file" >&2
            return 0
        fi
    done

    echo "No .env file found, using environment variables" >&2
    return 1
}

# Function to replace localhost with Docker host
replace_localhost() {
    local input_str="$1"
    local docker_host=""

    if ping -c 1 -w 1 host.docker.internal >/dev/null 2>&1; then
        docker_host="host.docker.internal"
        echo "Docker Desktop detected: Using host.docker.internal" >&2
    elif ping -c 1 -w 1 172.17.0.1 >/dev/null 2>&1; then
        docker_host="172.17.0.1"
        echo "Docker on Linux detected: Using 172.17.0.1" >&2
    else
        echo "WARNING: Cannot determine Docker host IP" >&2
        return 1
    fi

    if [[ -n "$docker_host" ]]; then
        local new_str="${input_str/localhost/$docker_host}"
        echo "  Remapping: $input_str --> $new_str" >&2
        echo "$new_str"
        return 0
    fi

    echo "$input_str"
    return 1
}

# Load environment variables
echo "=== Loading Configuration ===" >&2
load_env_file

# Replace localhost in DATABASE_URL if needed
if [[ -n "$DATABASE_URL" && "$DATABASE_URL" == *"postgres"*"://"*"localhost"* ]]; then
    echo "Found localhost in DATABASE_URL: $DATABASE_URL" >&2
    new_uri=$(replace_localhost "$DATABASE_URL")
    if [[ $? -eq 0 ]]; then
        export DATABASE_URI="$new_uri"
        export DATABASE_URL="$new_uri"
    fi
fi

# Replace localhost in DATABASE_URI if needed
if [[ -n "$DATABASE_URI" && "$DATABASE_URI" == *"postgres"*"://"*"localhost"* ]]; then
    echo "Found localhost in DATABASE_URI: $DATABASE_URI" >&2
    new_uri=$(replace_localhost "$DATABASE_URI")
    if [[ $? -eq 0 ]]; then
        export DATABASE_URI="$new_uri"
    fi
fi

# Display configuration summary
echo "" >&2
echo "=== Configuration Summary ===" >&2
echo "Database URL: ${DATABASE_URL:-"Not set"}" >&2
echo "Transport Mode: ${TRANSPORT:-"stdio"}" >&2
echo "Access Mode: ${ACCESS_MODE:-"unrestricted"}" >&2
echo "" >&2

if [[ -n "$NACOS_SERVER_ADDR" ]]; then
    echo "🚀 Nacos Integration: ENABLED" >&2
    echo "   Server: $NACOS_SERVER_ADDR" >&2
    echo "   Namespace: $NACOS_NAMESPACE" >&2
    echo "   Service Name: ${NACOS_SERVICE_NAME:-"postgres-mcp"}" >&2
    echo "" >&2
else
    echo "🏠 Standalone Mode: ENABLED" >&2
    echo "" >&2
fi

# Add default SSE host for HTTP transports if not set
if [[ "$TRANSPORT" == "sse" || "$TRANSPORT" == "streamable-http" ]]; then
    if [[ -z "$SSE_HOST" ]]; then
        echo "Setting default SSE host to 0.0.0.0" >&2
        export SSE_HOST="0.0.0.0"
    fi
    if [[ -z "$HTTP_PORT" ]]; then
        echo "Setting default HTTP port to $([ "$TRANSPORT" == "sse" ] && echo "8000" || echo "9001")" >&2
        export HTTP_PORT="$([ "$TRANSPORT" == "sse" ] && echo "8000" || echo "9001")"
    fi
fi

echo "=== Starting PostgreSQL MCP Server ===" >&2
echo "Transport: $([ "$TRANSPORT" == "stdio" ] && echo "stdio" || echo "$TRANSPORT (Port: $HTTP_PORT)")" >&2
if [[ -n "$NACOS_SERVER_ADDR" ]]; then
    echo "Nacos: $NACOS_SERVER_ADDR" >&2
fi
echo "========================================" >&2

# Execute the command with processed arguments
echo "Command: $*" >&2
exec "$@"